/*
 * @Author: ZhangPeng irocky@email.cn
 * @Date: 2023-01-11 22:24:21
 * @Description:
 * @RoutePath:
 * Copyright (c) 2023 by ${git_name}, All Rights Reserved.
 */
import type { Router, RouteRecordRaw, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { isHttp } from '@/utils/validate';
import { useUserStore } from '@/store';
import useRouteStore from '@/store/modules/route';
import { isLogin } from '@/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    if (isLogin()) {
      if (to.name === 'login') {
        next({
          name: 'Workplace',
        });
        return;
      }
      const userStore = useUserStore();
      if (userStore.roles.length) {
        next();
      } else {
        try {
          await useUserStore().info();
          const accessRoutes = await useRouteStore().generateRoutes();
          accessRoutes.forEach((route) => {
            if (!isHttp(route.path)) {
              router.addRoute(route as RouteRecordRaw); // 动态添加可访问路由表
            }
          });
          next({ path: to.path, query: to.query, replace: true }); // 重新跳转，避免404
        } catch (error) {
          await userStore.logout();
          next({
            name: 'login',
            query: {
              redirect: to.name,
              ...to.query,
            } as LocationQueryRaw,
          });
        }
      }
    } else {
      if (to.name === 'login') {
        next();
        return;
      }
      next({
        name: 'login',
        query: {
          redirect: to.name,
          ...to.query,
        } as LocationQueryRaw,
      });
    }
  });
  router.afterEach(() => {
    NProgress.done();
  });
}
